package midone.exchangeskill.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.concurrent.ExecutionException;


import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by NekoNeko on 2015/11/20.
 */
public class ViewUtils {
    Context context;

    public ViewUtils(Context context) {
        this.context = context;
    }

    /**
     * dp转px
     *
     * @param dpValue
     * @return
     */
    public float dip2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (dpValue * scale + 0.5f);
    }


    public void setTextViewTopDrawableBounds(TextView textView, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(null, drawable, null, null);
    }


    public void setTextRightDrawable(TextView textView, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        drawable.setBounds(0, 0, width, height);
        Drawable[] drawables = textView.getCompoundDrawables();
        drawables[2] = drawable;
        textView.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
    }


    /**
     * 设置网络图片为textView topDrawable
     *
     * @param textView
     * @param defaultDrawableId
     * @param url
     */
    public void setTextViewTopDrawableBound(TextView textView, int defaultDrawableId, String url) {
        Drawable drawable = ContextCompat.getDrawable(context, defaultDrawableId);
        try {
            Bitmap bitmap = Glide.with(context).load(url).asBitmap().into(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()).get();
            drawable = new BitmapDrawable(context.getResources(), bitmap);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        textView.setCompoundDrawables(drawable, null, null, null);
    }

    /**
     * 设置网络图片为textView topDrawable
     *
     * @param textView
     * @param drawable
     * @param url
     */
    public Subscription setTextTopDrawable(final TextView textView, final Drawable drawable, final String url) {
        Observable obs = Observable.create(new Observable.OnSubscribe<Bitmap>() {
            @Override
            public void call(Subscriber<? super Bitmap> subscriber) {
                try {
                    Bitmap bitmap = Glide.with(context).load(url).asBitmap().into(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()).get();
                    subscriber.onNext(bitmap);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        return obs.subscribe(new Action1<Bitmap>() {
            @Override
            public void call(Bitmap bitmap) {
                Drawable urlDrawable = new BitmapDrawable(context.getResources(), bitmap);
                urlDrawable.setBounds(0, 0, drawable.getIntrinsicHeight(), drawable.getIntrinsicWidth());
                textView.setCompoundDrawables(null, urlDrawable, null, null);
            }
        });

    }

    public void setTextViewLeftDrawable(TextView textView, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(drawable, null, null, null);
    }

    /**
     * 返回屏幕宽度
     *
     * @return
     */
    public int getScreenWidth() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        return width;
    }

    public int getScreenHeight() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        return height;
    }


    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale（DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public int sp2px(float spValue) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * scale + 0.5f);
    }

    /**
     * 图片放大
     *
     * @param scaleSize
     */
    public void scaleImage(float scaleSize, ImageView imageView) {
        imageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = imageView.getDrawingCache();
        if (bitmap == null || bitmap.isRecycled()) {
            return;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        width = (int) (scaleSize * width);
        height = (int) (scaleSize * height);
        Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
        bitmap.recycle();
        imageView.setImageBitmap(scaleBitmap);


    }


    /**
     * 获取版本号
     *
     * @return
     */
    public int getVersionCode() {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public String getVersionName() {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0";
        }
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyBoard(Activity context) {
        View focusView = context.getCurrentFocus();
        if (focusView != null && context.getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) context.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
